﻿using UnityEngine;
using Sfs2X;
using Sfs2X.Core;
using Sfs2X.Entities;
using Sfs2X.Requests;
using Sfs2X.Logging;
using Sfs2X.Entities.Data;

// Statics for holding the connection to the SFS server end
// Can then be queried from the entire game to get the connection

public class SmartFoxConnection : MonoBehaviour
{

    private static SmartFoxConnection mInstance;
    private static SmartFox smartFox;
    private static SFSObject persistentData;
    public static SmartFox Connection
    {
        get
        {
            if (mInstance == null)
            {
                mInstance = new GameObject("SmartFoxConnection").AddComponent(typeof(SmartFoxConnection)) as SmartFoxConnection;
            }
            return smartFox;
        }

        set
        {
            if (mInstance == null)
            {
                mInstance = new GameObject("SmartFoxConnection").AddComponent(typeof(SmartFoxConnection)) as SmartFoxConnection;
            }
            smartFox = value;
        }
    }
    public static SFSObject PersistentData
    {
        get
        {
            return persistentData;
        }

        set 
        {
            persistentData = value;
        }
    }

    public static bool IsInitialized
    {
        get
        {
            return (smartFox != null);
        }
    }

    public static void SendReadyMsg(SFSObject mParams){
        smartFox.Send(new ExtensionRequest(Commands.CMD_READY, mParams));
    }

    public static void SendMoveMsg(int x, int y){
        ISFSObject mParams = new SFSObject();
        mParams.PutInt("p_x", x);
        mParams.PutInt("p_y", y);
        mParams.PutInt("rID", smartFox.LastJoinedRoom.Id);
        smartFox.Send(new ExtensionRequest(Commands.CMD_MOVE, mParams));
    }

    // Handle disconnection automagically
    void OnApplicationQuit()
    {
        if (smartFox.IsConnected)
        {
            smartFox.Disconnect();
        }
    }
}
